package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.graphics.Color;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Fill;
import com.github.mikephil.charting.utils.MPPointF;
import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.util.DayAxisValueFormatter;
import com.laiyima.zhongjiang.linghuilv.demo.util.DemoBase;
import com.laiyima.zhongjiang.linghuilv.demo.util.MyValueFormatter;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.util.XYMarkerView;

import java.util.ArrayList;
import java.util.List;

public class IncomeStatisticActivity extends DemoBase implements View.OnClickListener, SeekBar.OnSeekBarChangeListener,
        OnChartValueSelectedListener {
    private String TAG="";
    private int isCode;
    private LinearLayout imageView;
    private LinearLayout day_is,moth_is,year_is,leiji_is;
    private TextView day_lin,moth_lin,year_lin,leiji_lin;
    private TextView day_text,moth_text,year_text,leiji_text;
    private TextView show_gety;


    private BarChart chart;
    private SeekBar seekBarX, seekBarY;
    private TextView tvX, tvY;

    private TimeUtils timeUtils;
    private String YY,MM,DD;
    private String label;

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_income_statistic);
        imageView= (LinearLayout) findViewById(R.id.is_back);
        day_is= (LinearLayout) findViewById(R.id.is_day);
        moth_is= (LinearLayout) findViewById(R.id.is_moth);
        year_is= (LinearLayout) findViewById(R.id.is_year);
        leiji_is= (LinearLayout) findViewById(R.id.is_leiji);
        day_lin= (TextView) findViewById(R.id.day_lin);
        moth_lin= (TextView) findViewById(R.id.moth_lin);
        year_lin= (TextView) findViewById(R.id.year_lin);
        leiji_lin= (TextView) findViewById(R.id.leiji_lin);
        day_text= (TextView) findViewById(R.id.is_day_text);
        moth_text= (TextView) findViewById(R.id.is_moth_text);
        year_text= (TextView) findViewById(R.id.is_year_text);
        leiji_text= (TextView) findViewById(R.id.is_leiji_text);
        show_gety= (TextView) findViewById(R.id.show_getY);


        day_is.setOnClickListener(this);
        moth_is.setOnClickListener(this);
        year_is.setOnClickListener(this);
        leiji_is.setOnClickListener(this);
        imageView.setOnClickListener(this);


        YY=timeUtils.getCurrentTimeyy();

        MM=getInt(timeUtils.getCurrentTimemm());

        DD=getInt(timeUtils.getCurrentTimedd());

        label=MM+"月份";


        tvX = (TextView) findViewById(R.id.tvXMax);
        tvY = (TextView) findViewById(R.id.tvYMax);

        seekBarX = (SeekBar) findViewById(R.id.seekBar1);
        seekBarY = (SeekBar) findViewById(R.id.seekBar2);

        seekBarY.setOnSeekBarChangeListener(this);
        seekBarX.setOnSeekBarChangeListener(this);

        chart = (BarChart) findViewById(R.id.chart1);
        chart.setOnChartValueSelectedListener(this);

        chart.setDrawBarShadow(false);
        chart.setDrawValueAboveBar(true);

        chart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        chart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        chart.setPinchZoom(false);

         chart.setDrawGridBackground(false);
        // chart.setDrawYLabels(false);

        ValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTypeface(tfLight);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(xAxisFormatter);

        ValueFormatter custom = new MyValueFormatter("¥");

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setTypeface(tfLight);
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setTypeface(tfLight);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);

        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(chart); // For bounds control
        chart.setMarker(mv); // Set the marker to the chart

        // setting data
        seekBarY.setProgress(100);
        seekBarX.setProgress(12);
        setStatusBar();
    }



    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.is_back:
                finish();
                break;
            case R.id.is_day:
                setData(seekBarX.getProgress(), seekBarY.getProgress());
                chart.invalidate();
                day_text.setTextColor(Color.parseColor("#126AE4"));
                day_lin.setBackgroundColor(Color.parseColor("#126AE4"));
                moth_text.setTextColor(Color.parseColor("#B8B8B8"));
                moth_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                year_text.setTextColor(Color.parseColor("#B8B8B8"));
                year_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                leiji_text.setTextColor(Color.parseColor("#B8B8B8"));
                leiji_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                break;
            case R.id.is_moth:
                label=YY+"年";
                tvX.setText(String.valueOf(seekBarX.getProgress()));
                tvY.setText(String.valueOf(seekBarY.getProgress()));
                setData(seekBarX.getProgress(), seekBarY.getProgress());
                chart.invalidate();

                moth_text.setTextColor(Color.parseColor("#126AE4"));
                moth_lin.setBackgroundColor(Color.parseColor("#126AE4"));
                day_text.setTextColor(Color.parseColor("#B8B8B8"));
                day_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                year_text.setTextColor(Color.parseColor("#B8B8B8"));
                year_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                leiji_text.setTextColor(Color.parseColor("#B8B8B8"));
                leiji_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                break;
            case R.id.is_year:
                setData(seekBarX.getProgress(), seekBarY.getProgress());
                chart.invalidate();
                year_text.setTextColor(Color.parseColor("#126AE4"));
                year_lin.setBackgroundColor(Color.parseColor("#126AE4"));
                day_text.setTextColor(Color.parseColor("#B8B8B8"));
                day_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                moth_text.setTextColor(Color.parseColor("#B8B8B8"));
                moth_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                leiji_text.setTextColor(Color.parseColor("#B8B8B8"));
                leiji_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                break;
            case R.id.is_leiji:
                setData(seekBarX.getProgress(), seekBarY.getProgress());
                chart.invalidate();
                leiji_text.setTextColor(Color.parseColor("#126AE4"));
                leiji_lin.setBackgroundColor(Color.parseColor("#126AE4"));
                day_text.setTextColor(Color.parseColor("#B8B8B8"));
                day_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                moth_text.setTextColor(Color.parseColor("#B8B8B8"));
                moth_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                year_text.setTextColor(Color.parseColor("#B8B8B8"));
                year_lin.setBackgroundColor(Color.parseColor("#F2F2F2"));
                break;
        }

    }






    private void setData(int count, float range) {

        float start = 1f;

        ArrayList<BarEntry> values = new ArrayList<>();

        for (int i = (int) start; i < start + count; i++) {
            float val = (float) (Math.random() * (range + 1));

            if (Math.random() * 100 < 25) {
                values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star)));
            } else {
                values.add(new BarEntry(i, val));
            }
        }

        BarDataSet set1;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();

        } else {

            set1 = new BarDataSet(values, label);
            set1.setColor(Color.rgb(240, 85, 46));
            set1.setDrawIcons(false);
            set1.setHighLightColor(Color.rgb(255, 187, 115));


            int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor2 = ContextCompat.getColor(this, android.R.color.holo_blue_light);
            int startColor3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor4 = ContextCompat.getColor(this, android.R.color.holo_green_light);
            int startColor5 = ContextCompat.getColor(this, android.R.color.holo_red_light);
            int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
            int endColor2 = ContextCompat.getColor(this, android.R.color.holo_purple);
            int endColor3 = ContextCompat.getColor(this, android.R.color.holo_green_dark);
            int endColor4 = ContextCompat.getColor(this, android.R.color.holo_red_dark);
            int endColor5 = ContextCompat.getColor(this, android.R.color.holo_orange_dark);

            List<Fill> gradientFills = new ArrayList<>();
            gradientFills.add(new Fill(startColor1, endColor1));
            gradientFills.add(new Fill(startColor2, endColor2));
            gradientFills.add(new Fill(startColor3, endColor3));
            gradientFills.add(new Fill(startColor4, endColor4));
            gradientFills.add(new Fill(startColor5, endColor5));

         //   set1.setFills(gradientFills);

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(tfLight);
            data.setBarWidth(0.4f);

             chart.setData(data);
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        tvX.setText(String.valueOf(seekBarX.getProgress()));
        tvY.setText(String.valueOf(seekBarY.getProgress()));
        setData(seekBarX.getProgress(), seekBarY.getProgress());
        chart.invalidate();
    }

    @Override
    protected void saveToGallery() {
        saveToGallery(chart, "BarChartActivity");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}

    private final RectF onValueSelectedRectF = new RectF();

    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;

        RectF bounds = onValueSelectedRectF;
        chart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = chart.getPosition(e, YAxis.AxisDependency.LEFT);
        show_gety.setText((int)h.getY()+"");
        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        Log.i("x-index",
                "low: " + chart.getLowestVisibleX() + ", high: "
                        + chart.getHighestVisibleX());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() { }

    private String getInt(String s){
        String o=s.substring(0,1);
        String t=s.substring(1,2);
        if(o.equals("0")){
            s=t;
        }
        return s;
    }
}
